// src/message/Message.tsx
import React, { useState, useEffect } from 'react';
import { Layout, Button, Tabs, Badge, Spin, message as antMessage } from 'antd';
import Sidebar from '../Sidebar';
import MessageList from './MessageList';

const { Header, Content } = Layout;     

interface UserMessage {
  id: number;
  userId: number;
  fromUserId: number;
  type: 'favorite' | 'recipe_comment' | 'comment_like' | 'follow';
  referenceId: number;
  content: string;
  readFlag: boolean;
  createdAt: string;
}

const Message: React.FC = () => {
  const [activeTab, setActiveTab] = useState<string>('all');
  const [messages, setMessages] = useState<UserMessage[]>([]);
  const [loading, setLoading] = useState(true);
  const [markingAsRead, setMarkingAsRead] = useState(false);

  // 颜色配置 - 统一使用棕色系
  const colorConfig = {
    primary: '#e8d9c7',
    primaryDark: '#8b4513',
    border: '#d4b896',
    background: '#f8f4f0',
    badge: '#a0522d',
    tabActive: '#e8d9c7',
  };

  // 获取当前用户ID
  const getUserId = (): number => {
    const userId = localStorage.getItem('userId');
    return userId ? parseInt(userId) : 0;
  };

  // 构建 API 基础 URL - 修复：直接使用后端地址
  const getApiBaseUrl = (): string => {
    return 'http://218.244.141.86:8080/api';
  };

  // 获取所有消息
  const fetchAllMessages = async (): Promise<UserMessage[]> => {
    try {
      const userId = getUserId();
      const token = localStorage.getItem('token') || sessionStorage.getItem('token');
      
      if (!userId || !token) {
        antMessage.warning('请先登录');
        return [];
      }

      const baseUrl = getApiBaseUrl();
      const apiUrl = `${baseUrl}/usermessages/user/${userId}`;

      const response = await fetch(apiUrl, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        mode: 'cors',
        credentials: 'include'
      });

      if (response.ok) {
        const responseText = await response.text();
        
        if (!responseText || responseText.trim() === '') {
          return [];
        }
        
        try {
          const data = JSON.parse(responseText);
          
          if (Array.isArray(data)) {
            const sortedData = data.sort((a: UserMessage, b: UserMessage) => 
              new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
            );
            return sortedData;
          } else {
            if (data && typeof data === 'object') {
              return [data];
            }
            return [];
          }
        } catch (jsonError) {
          console.error('JSON解析错误:', jsonError);
          antMessage.error('数据格式错误');
          return [];
        }
      } else {
        console.error('获取消息失败:', response.status, response.statusText);
        antMessage.error(`获取消息失败: ${response.status}`);
        return [];
      }
    } catch (error) {
      console.error('获取消息时网络错误:', error);
      antMessage.error('获取消息失败，请检查网络连接');
      return [];
    }
  };

  // 标记所有消息为已读
  const markAllAsRead = async (): Promise<boolean> => {
    try {
      const userId = getUserId();
      const token = localStorage.getItem('token') || sessionStorage.getItem('token');
      
      if (!userId || !token) {
        antMessage.warning('用户未登录');
        return false;
      }

      if (getUnreadCountByType('all') === 0) {
        antMessage.info('没有未读消息需要标记');
        return true;
      }

      setMarkingAsRead(true);

      const baseUrl = getApiBaseUrl();
      const apiUrl = `${baseUrl}/usermessages/user/${userId}/read-all`;

      const response = await fetch(apiUrl, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
        mode: 'cors',
        credentials: 'include'
      });

      if (response.ok) {
        antMessage.success('所有消息已标记为已读');
        setMessages(prev => prev.map(msg => ({ ...msg, readFlag: true })));
        return true;
      } else {
        if (response.status === 403) {
          antMessage.error('权限不足，无法标记消息为已读');
        } else {
          antMessage.error(`标记已读失败: ${response.status}`);
        }
        return false;
      }
    } catch (error) {
      console.error('标记已读时网络错误:', error);
      antMessage.error('标记已读失败，请检查网络连接');
      return false;
    } finally {
      setMarkingAsRead(false);
    }
  };

  // 标记单条消息为已读
  const markMessageAsRead = async (messageId: number): Promise<void> => {
    try {
      setMessages(prev => prev.map(msg => 
        msg.id === messageId ? { ...msg, readFlag: true } : msg
      ));
    } catch (error) {
      console.error('标记单条消息为已读时出错:', error);
    }
  };

  // 加载消息数据
  const loadMessages = async () => {
    setLoading(true);
    try {
      const userId = getUserId();
      const cachedMessages = localStorage.getItem(`user_${userId}_messages`);
      
      if (cachedMessages) {
        try {
          const parsedMessages = JSON.parse(cachedMessages);
          setMessages(parsedMessages);
        } catch (e) {
          console.error('解析缓存消息失败:', e);
        }
      }
      
      const allMessages = await fetchAllMessages();
      if (allMessages.length > 0) {
        setMessages(allMessages);
        localStorage.setItem(`user_${userId}_messages`, JSON.stringify(allMessages));
      }
    } catch (error) {
      console.error('加载消息数据时出错:', error);
    } finally {
      setLoading(false);
    }
  };

  // 根据消息类型过滤消息 - 更新逻辑以包含收藏
  const filterMessagesByType = (type: string): UserMessage[] => {
    if (type === 'all') return messages;
    
    const typeMap: { [key: string]: string[] } = {
      'like': ['comment_like'], // 只包含评论点赞
      'favorite': ['favorite'], // 新增：收藏消息
      'reply': ['recipe_comment'], // 评论
      'follow': ['follow'] // 关注
    };
    
    const backendTypes = typeMap[type] || [type];
    return messages.filter(msg => backendTypes.includes(msg.type));
  };

  // 获取未读消息数量
  const getUnreadCountByType = (type: string): number => {
    const filteredMessages = filterMessagesByType(type);
    return filteredMessages.filter(msg => !msg.readFlag).length;
  };

  // 组件挂载时加载消息
  useEffect(() => {
    loadMessages();
  }, []);

  // 刷新消息
  const handleRefresh = () => {
    loadMessages();
  };

  // 处理标记所有为已读
  const handleMarkAllAsRead = async () => {
    await markAllAsRead();
  };

  // 定义消息类型配置 - 添加收藏标签
  const tabItems = [
    { 
      key: 'all', 
      label: (
        <Badge count={getUnreadCountByType('all')} size="small" offset={[10, -5]}>
          全部消息
        </Badge>
      )
    },
    { 
      key: 'favorite', 
      label: (
        <Badge count={getUnreadCountByType('favorite')} size="small" offset={[10, -5]}>
          收藏
        </Badge>
      )
    },
    { 
      key: 'like', 
      label: (
        <Badge count={getUnreadCountByType('like')} size="small" offset={[10, -5]}>
          点赞
        </Badge>
      )
    },
    { 
      key: 'reply', 
      label: (
        <Badge count={getUnreadCountByType('reply')} size="small" offset={[10, -5]}>
          评论
        </Badge>
      )
    },
    { 
      key: 'follow', 
      label: (
        <Badge count={getUnreadCountByType('follow')} size="small" offset={[10, -5]}>
          关注
        </Badge>
      )
    }
  ];

  return (
    <Layout style={{ 
      minHeight: '100vh', 
      backgroundImage: "url('/background2.jpg')",
      backgroundSize: 'cover',
      backgroundPosition: 'center',
    }}>
      <Sidebar />
      
      <Layout style={{ background: 'transparent' }}>
        <Header style={{
          background: 'white',
          boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
          padding: '0 40px',
          height: 'auto',
          lineHeight: '64px',
          borderRadius: '12px 12px 0 0',
          margin: '20px 40px 0 40px',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <h2 style={{ margin: 0, fontSize: '24px', fontWeight: 'bold', color: colorConfig.primaryDark }}>
            消息中心
          </h2>
          <div style={{ display: 'flex', gap: '12px' }}>
            <Button 
              type="default"
              style={{
                borderRadius: '20px',
                fontWeight: 'bold',
                borderColor: colorConfig.border,
                color: colorConfig.primaryDark
              }}
              onClick={handleRefresh}
              disabled={loading}
            >
              {loading ? '加载中...' : '刷新消息'}
            </Button>
            <Button 
              type="primary"
              style={{
                backgroundColor: colorConfig.primary,
                borderColor: colorConfig.primary,
                color: colorConfig.primaryDark,
                borderRadius: '20px',
                fontWeight: 'bold'
              }}
              onClick={handleMarkAllAsRead}
              disabled={getUnreadCountByType('all') === 0 || markingAsRead}
              loading={markingAsRead}
            >
              标记所有为已读 ({getUnreadCountByType('all')})
            </Button>
          </div>
        </Header>

        <Content style={{ 
          margin: '0 40px 20px 40px',
          padding: '0',
          background: 'transparent',
        }}>
          <div style={{
            background: 'white',
            padding: '24px',
            borderRadius: '0 0 12px 12px',
            minHeight: 'calc(100vh - 200px)'
          }}>
            <div style={{ 
              overflowX: 'auto', 
              paddingBottom: '8px',
              scrollbarWidth: 'thin',
              scrollbarColor: `${colorConfig.primary} transparent`
            }}>
              <Tabs
                activeKey={activeTab}
                onChange={setActiveTab}
                type="card"
                items={tabItems.map(item => ({
                  ...item,
                  label: (
                    <span style={{ color: colorConfig.primaryDark }}>
                      {item.label}
                    </span>
                  )
                }))}
                style={{
                  ['--antd-tab-active-color' as any]: colorConfig.primaryDark,
                  ['--antd-tab-ink-bar-color' as any]: colorConfig.primary,
                  minWidth: 'max-content'
                }}
              />
            </div>

            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <Spin size="large" style={{ color: colorConfig.primary }} />
                <div style={{ marginTop: '16px', color: colorConfig.primaryDark }}>
                  加载消息中...
                </div>
              </div>
            ) : (
              <MessageList
                messages={filterMessagesByType(activeTab)}
                activeTab={activeTab}
                onMarkMessageAsRead={markMessageAsRead}
                colorConfig={colorConfig}
              />
            )}
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default Message;